package com.ljs.redisall.willow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljs.redisall.willow.entity.Emp;
import com.ljs.redisall.willow.exception.handler.DataResult;
import com.ljs.redisall.willow.service.EmpService;
import com.ljs.redisall.willow.util.RedisUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class RedisController {
    @Resource
    RedisUtils redisUtils;
    @Resource
    EmpService empService;

    @RequestMapping("/selall")
    public DataResult testredis() {

        DataResult dataResult = new DataResult();
        String kk = "emplist1";

        //先查redis里有没有
        List<Emp> emplist = null;
        String empliststr = (String) redisUtils.get(kk);//转化为string
        System.out.println("empliststr"+empliststr);
        if (empliststr == null || empliststr.equals("")) {
            System.out.println("redis没有");
            emplist = empService.selall();
            System.out.println("从数据库查" + emplist);
            if(emplist.size()>0){//不能存空值进去了
                redisUtils.set(kk, JSON.toJSONString(emplist));//将list变为json格式
            }


        } else {
            //有
            emplist = JSONObject.parseArray(empliststr, Emp.class);//转化为list
            System.out.println("从redis查" + emplist);

        }

        dataResult.setData(emplist);
        return dataResult;
    }

    @RequestMapping("/login")

    public DataResult login(HttpServletRequest request, @RequestParam("phone") String phone, @RequestParam("password") String password) {
        System.out.println("登录顶顶顶顶");

        DataResult jsonResult = new DataResult();
        System.out.println("电话是" + phone);
        System.out.println("密码是" + password);
        String ukk="emp3"+phone+password;
        Emp emp=null;
              String users  = (String) redisUtils.get(ukk);
        System.out.println("users是"+users);//是字符串的null
              if(users==null || users.equals("")){
                  emp=empService.login(phone,password);
                  //存入redis
                  System.out.println("从数据库"+emp);
                  if(emp!=null){//查出的值不为空才存
                      redisUtils.set(ukk,JSON.toJSONString(emp));
                  }


       }else {
                  System.out.println("从redis查");
                  emp=JSONObject.parseObject(users,Emp.class);

       }
        System.out.println("最后的"+emp);
       if(emp==null){
           jsonResult.setMsg("登录失败");
       }else {
           jsonResult.setData(emp);
       }

        return jsonResult;
    }
}
